<?php
declare(strict_types=1);

namespace App\Logic\Resource;

use App\Logic\BaseUserService;
use App\Model\User\Resource\UserSource;
use Closure;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/5/25
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class ResourceService extends BaseUserService
{
    private static function searchWhere(): Closure
    {
        return function ($query) {
            $requestParams = request()->all();
            $query->where("is_show", "=", 1);
            if (!empty($requestParams["category_uid"])) {
                $query->where("category_uid", "=", $requestParams["category_uid"]);
            }
            if (!empty($requestParams["uid"])) {
                $query->where("uid", "=", $requestParams["uid"]);
            }
            if (!empty($requestParams["title"])) {
                $query->where("title", "like", "%{$requestParams["title"]}%");
            }
        };
    }

    public function getList(): array
    {
        $requestParams = request()->all();
        $queryField = ["uid", "title", "price", "is_free", "remark", "download_count", "source", "category_uid", "url", "path"];
        $items = UserSource::query()
            ->with(["category:uid,title"])
            ->where(self::searchWhere())
            ->orderByDesc("sort")
            ->orderByDesc("id")
            ->paginate((int)($requestParams["size"] ?? 20), $queryField);

        return [
            "items" => $items->items(),
            "page" => $items->currentPage(),
            "size" => (int)($requestParams["size"] ?? 20),
            "total" => $items->total(),
        ];
    }

    public function getContent(): array
    {
        $queryField = ["uid", "title", "price", "is_free", "remark", "download_count", "source", "category_uid", "url", "path", "content"];
        $bean = UserSource::query()
            ->with(["category:uid,title"])
            ->where(self::searchWhere())
            ->first($queryField);
        if (!empty($bean)) {
            $bean = $bean->toArray();
            $bean["app_state"] = env("APP_STATE");
            return $bean;
        }
        return [];
    }

    public function getDownLoadUrl(): array
    {
        $bean = UserSource::query()->where(self::searchWhere())->first(["download_url", "is_free"]);
        if (!empty($bean)) {
            UserSource::query()->where([["uid", "=", request()->get("uid")]])->increment("download_count");
            if ($this->getVipState()) {
                return ["isVip" => false, "download_url" => $bean->download_url, "url" => "/subpages/user/member/describe", "is_free" => $bean->is_free];
            } else {
                return ["isVip" => false, "download_url" => "", "url" => "/subpages/user/member/describe", "is_free" => $bean->is_free];
            }
        }
        return [];
    }
}
